package com.ihg.hiex.admin.web.controller.session.preparation;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.web.interceptor.MenuSetting;
import com.ihg.hiex.admin.entity.security.Login;
import com.ihg.hiex.admin.service.account.AdministratorService;
import com.ihg.hiex.admin.service.session.ConferenceRoomService;
import com.ihg.hiex.admin.service.session.FinalTestService;
import com.ihg.hiex.admin.service.session.SessionMeetingService;
import com.ihg.hiex.admin.service.session.SessionService;
import com.ihg.hiex.admin.service.session.SessionTaskService;
import com.ihg.hiex.admin.web.resolver.Secure;
import com.ihg.hiex.entity.data.conference.ConferenceRoom;
import com.ihg.hiex.entity.session.Session;
import com.ihg.hiex.entity.session.before.finaltest.FinalTest;
import com.ihg.hiex.entity.session.before.finaltest.FinalTestExercise;
import com.ihg.hiex.entity.session.meeting.SessionMeeting;
import com.ihg.hiex.entity.session.participator.Type;
import com.ihg.hiex.entity.session.task.SessionTask;
import com.ihg.hiex.entity.user.Administrator;
import com.ihg.hiex.entity.user.Assessor;
import com.ihg.hiex.entity.user.Delegate;

/**
 * Session 准备阶段首页
 * 
 * @author dan
 *
 */
@Controller
@RequestMapping("/sessions/{sessionId}")
@MenuSetting("menu-sessions")
public class PreparationHomeController {
    
    private static final Logger logger = LoggerFactory.getLogger(PreparationHomeController.class);
    
    @Autowired
    private SessionService sessionService;
    
    @Autowired
    private SessionMeetingService sessionMeetingService;
    
    @Autowired
    private AdministratorService administratorService;
    
    @Autowired
    private SessionTaskService sessionTaskService;
    
    @Autowired
    private FinalTestService finalTestService;
    
    @Autowired
    private ConferenceRoomService conferenceRoomService;
    
    /**
     * preparation home
     * 
     * @param login
     * @param sessionId
     * @return
     */
    @RequestMapping(value = "/preparation-home", method = RequestMethod.GET)
    @MenuSetting("submenu-session-preparation-home")
    public ModelAndView view(@Secure Login login, @PathVariable("sessionId") Long sessionId) {
        
        ModelAndView modelAndView = new ModelAndView("session/preparation/home/session-preparation-home");
        
        Session session = sessionService.load(sessionId);
        modelAndView.addObject("session", session);
        
        // 1. list session's all meeting
        Map<String, Map<String, SessionMeeting>> sessionMeetings = sessionService.listSessionMeeting(session);
        modelAndView.addObject("sessionMeetings", sessionMeetings);
        
        // 2.1 list assessors
        List<Assessor> assessors = sessionService.listAssessor(session);
        modelAndView.addObject("assessors", assessors);
        
        // 2.2 list assessor's session task
        Map<String, Map<String, SessionTask>> assessorTasks = sessionService.listSessionTaks(session, Type.ASSESSOR);
        modelAndView.addObject("assessorTasks", assessorTasks);
        
        // 3.1 list delegates;
        List<Delegate> delegates = sessionService.listDelegate(session);
        modelAndView.addObject("delegates", delegates);
        
        // 3.2 list delegate's session task
        Map<String, Map<String, SessionTask>> delegateTasks = sessionService.listSessionTaks(session, Type.DELEGATE);
        modelAndView.addObject("delegateTasks", delegateTasks);
        
        // 4.1 get traing-modules finish count, Map<assessorId, finishCount>
        List<String> traingTaskNames = Arrays.asList("How to evaluate delegates", "What are the exercises", "How to write the report");
        Map<String, Integer> traingTasks = sessionTaskService.listFinishTask(session, traingTaskNames, Type.ASSESSOR);
        modelAndView.addObject("traingTasks", traingTasks);
        
        // 4.2 get final-test status
        Map<String, FinalTest> finalTestMap = finalTestService.list(session);
        modelAndView.addObject("finalTestMap", finalTestMap);
        
        // 4.3 get final test exercise status
        Map<String, List<FinalTestExercise>> finalTestExercises = finalTestService.listExercise(session);
        modelAndView.addObject("finalTestExercises", finalTestExercises);
        
        return modelAndView;
        
    }
    
    /**
     * edit meeting panel
     * 
     * @param sessionId
     * @param meetingId
     * @return
     */
    @RequestMapping(value = "/meetings/{meetingId}/edit", method = RequestMethod.GET, params="type=orientation")
    public ModelAndView editOrientation(@PathVariable("sessionId") Long sessionId,
                                        @PathVariable("meetingId") Long meetingId) {
        
        ModelAndView modelAndView = new ModelAndView("session/preparation/home/session-orientation-call-edit");

        Session session = sessionService.load(sessionId);
        modelAndView.addObject("session", session);
        
        // 1. load meeting
        SessionMeeting sessionMeeting = sessionMeetingService.load(SessionMeeting.class, meetingId);
        modelAndView.addObject("sessionMeeting", sessionMeeting);
        
        // 2. list administrator
        List<Administrator> administrators = administratorService.listAll(Administrator.class);
        modelAndView.addObject("administrators", administrators);
        
        return modelAndView;
        
    }
    
    /**
     * on edit meeting panel
     * 
     * @param meetingId
     * @param startTime
     * @param endTime
     * @param meetingHostId
     * @return
     */
    @RequestMapping(value = "/meetings/{meetingId}", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params="type=orientation")
    public @ResponseBody HttpResult onEditOrientation(@PathVariable("meetingId") Long meetingId,
                                                      @RequestParam("startTime") String startTime,
                                                      @RequestParam("endTime") String endTime,
                                                      @RequestParam("meetingHostId") Long meetingHostId) {
        
        HttpResult httpResult = new HttpResult();
        
        try {
            
            SessionMeeting sessionMeeting = sessionMeetingService.load(SessionMeeting.class, meetingId);
            Administrator sessionHost = administratorService.load(Administrator.class, meetingHostId);
            
            sessionTaskService.editOrientationTask(sessionMeeting, meetingHostId, sessionHost.getConferenceRoom(), startTime, endTime);
//            if (StringUtils.equals("orientation", type)) {
//                
//                // 1. edit metting
//                sessionTaskService.editOrientationTask(sessionMeeting, meetingHostId, sessionHost.getConferenceRoom(), startTime, endTime);
//                
//            } else if (StringUtils.equals("qa", type)) {
//                
//              // 1. edit metting
//              sessionTaskService.editQAndACallTask(sessionMeeting, meetingHostId, sessionHost.getConferenceRoom(), startTime, endTime);
//              
//            }
            
            httpResult.success().message("修改会议成功");
            
        } catch (Exception e) {
            logger.error("#onEditMeeting() - edit fail, exception=[{}]", e);
            httpResult.success().message("修改会议失败");
        }
        
        return httpResult;
        
    }
    
    /**
     * edit meeting panel
     * 
     * @param sessionId
     * @param meetingId
     * @return
     */
    @RequestMapping(value = "/meetings/{meetingId}/edit", method = RequestMethod.GET, params="type=qa")
    public ModelAndView editQa(@PathVariable("sessionId") Long sessionId,
                               @PathVariable("meetingId") Long meetingId) {
        
        ModelAndView modelAndView = new ModelAndView("session/preparation/home/session-qa-call-edit");

        Session session = sessionService.load(sessionId);
        modelAndView.addObject("session", session);
        
        // 1. load meeting
        SessionMeeting sessionMeeting = sessionMeetingService.load(SessionMeeting.class, meetingId);
        modelAndView.addObject("sessionMeeting", sessionMeeting);
        
        // 2. list administrator
        List<Administrator> administrators = administratorService.listAll(Administrator.class);
        modelAndView.addObject("administrators", administrators);
        
        // 3. list ConferenceRoom
        List<ConferenceRoom> conferenceRooms = conferenceRoomService.list(com.ihg.hiex.entity.data.conference.Type.BigZoom);
        modelAndView.addObject("conferenceRooms", conferenceRooms);
        
        return modelAndView;
        
    }
    
    /**
     * on edit meeting panel
     * 
     * @param meetingId
     * @param startTime
     * @param endTime
     * @param meetingHostId
     * @return
     */
    @RequestMapping(value = "/meetings/{meetingId}", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params="type=qa")
    public @ResponseBody HttpResult onEditQa(@PathVariable("meetingId") Long meetingId,
                                             @RequestParam("startTime") String startTime,
                                             @RequestParam("endTime") String endTime,
                                             @RequestParam("meetingHostId") Long meetingHostId,
                                             @RequestParam("conferenceRoomId") Long conferenceRoomId) {
        
        HttpResult httpResult = new HttpResult();
        
        try {
            
            SessionMeeting sessionMeeting = sessionMeetingService.load(SessionMeeting.class, meetingId);
            Administrator sessionHost = administratorService.load(Administrator.class, meetingHostId);
            ConferenceRoom conferenceRoom = conferenceRoomService.load(ConferenceRoom.class, conferenceRoomId);
            
            // 1. edit metting
            sessionTaskService.editQAndACallTask(sessionMeeting, meetingHostId, conferenceRoom, startTime, endTime);
              
            httpResult.success().message("修改会议成功");
            
        } catch (Exception e) {
            logger.error("#onEditMeeting() - edit fail, exception=[{}]", e);
            httpResult.success().message("修改会议失败");
        }
        
        return httpResult;
        
    }
    
    /**
     * 
     * @param sessionId
     * @return
     */
    @RequestMapping(value = "/open-notice", method = RequestMethod.GET)
    public ModelAndView openNotice(@PathVariable("sessionId") Long sessionId) {
        
        ModelAndView modelAndView = new ModelAndView("session/preparation/home/session-open-notice");

        Session session = sessionService.load(sessionId);
        modelAndView.addObject("session", session);
        
        return modelAndView;
        
    }
    
    /**
     * 
     * @param login
     * @param sessionId
     * @return
     */
    @RequestMapping(value = "/open-notice", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult onOpenNotice(@Secure Login login, @PathVariable("sessionId") Long sessionId) {
        
        HttpResult httpResult = new HttpResult();
        
        try {
            
            Session session = sessionService.load(sessionId);
            sessionService.openNotice(session, login.getId(), login.getName());
            
            httpResult.success().message("开启邮件通知成功");
            
        } catch (Exception e) {
            logger.error("#onOpenNotice() - edit fail, exception=[{}]", e);
            httpResult.success().message("开启邮件通知失败");
        }
        
        return httpResult;
        
    }
    
}
